<template>
  <div style="min-height: 100vh; background-color: #f5f5f7">
    <div class="page paydemo">
      <div class="blog-container" id="container" v-if="initRender">
        <a-spin :spinning="confirmLoading">
          <div class="content" v-if="baomingIsOpen">
            <div style="padding: 10px 10px; font-size: 26px; text-align: center;">罗田理工中等专业学校</div>
            <div style="width: 100%">
              <div class="paydemo-type-content">
                <div class="paydemo-type-name">报名缴费</div>
                <a-form ref="formRef" :model="formState" labelAlign="left"
                  :label-col="{ style: { minWidth: '90px', flex: 0 } }" :wrapper-col="{ style: { flex: 1 } }"
                  :rules="rules">
                  <a-form-item label="年级" name="grade">
                    <a-radio-group v-model:value="formState.grade" @change="gradeChange">
                      <a-radio :value="item.value" v-for="(item, index) in gradeList" :key="index">
                        {{ item.label }}
                      </a-radio>
                    </a-radio-group>
                  </a-form-item>

                  <a-form-item label="姓名" name="name">
                    <a-input :maxlength="20" v-model:value="formState.name" />
                  </a-form-item>

                  <a-form-item label="身份证" name="idCard">
                    <div class="flex">
                      <a-input :maxlength="18" v-model:value="formState.idCard" />

                    </div>
                  </a-form-item>

                  <template v-if="formState.grade === 1 && baomingAutumn">
                    <a-form-item label="准考证号" name="ticketNumber">
                      <div class="flex">
                        <a-input :maxlength="30" v-model:value="formState.ticketNumber" />
                        <a-button type="primary" :disabled="!formState.ticketNumber"
                          @click="handerTicketNumber">报名查询</a-button>
                      </div>
                    </a-form-item>

                    <a-form-item label="电话" name="phone">
                      <div class="flex">
                        <a-input :maxlength="20" v-model:value="formState.phone" />
                      </div>
                    </a-form-item>

                    <a-form-item label="联系人" name="contacts">
                      <div class="flex">
                        <a-input :maxlength="20" v-model:value="formState.contacts" />
                      </div>
                    </a-form-item>

                    <a-form-item label="联系人电话" name="contactsPhone">
                      <div class="flex">
                        <a-input :maxlength="20" v-model:value="formState.contactsPhone" />
                      </div>
                    </a-form-item>

                    <a-form-item label="联系地址" name="addr">
                      <div class="flex">
                        <a-input :maxlength="80" v-model:value="formState.addr" />
                      </div>
                    </a-form-item>
                  </template>

                  <a-form-item label="专业" name="specialityId" v-if="formState.grade == 1">
                    <a-select v-model:value="formState.specialityId" style="min-width: 200px;">
                      <a-select-option :value="item.id" v-for="item in specialityList" :key="item.id">{{
        item.specialityName }}({{ item.num }})
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="代收费" name="collectFees">
                    <a-radio-group v-model:value="formState.collectFees">
                      <a-radio :value="870" :disabled="formState.grade == 3" :style="radioStyle">870元（高一、高二）</a-radio>
                      <a-radio :value="950" :disabled="formState.grade != 3" :style="radioStyle">950元（高三）</a-radio>
                    </a-radio-group>
                  </a-form-item>

                  <a-form-item label="住宿费" name="accDation">
                    <a-radio-group v-model:value="formState.accDation">
                      <a-radio :value="0" :style="radioStyle">0元（不住宿）</a-radio>
                      <a-radio :value="430" :style="radioStyle">430元（1，3，5，7栋）</a-radio>
                      <a-radio :value="630" :style="radioStyle">630元（6栋）</a-radio>
                    </a-radio-group>
                  </a-form-item>

                  <a-form-item label="支付方式" name="channel">
                    <a-radio-group v-model:value="formState.channel">
                      <a-radio value="wechat_pay"
                        v-if="payChannelList.find(item => { return item.code == 'wechat_pay' })">
                        <div class="flex items-center">
                          <WechatOutlined :style="{ fontSize: '20px', color: '#22AC38' }" />
                          <span style="margin-left: 4px;">微信</span>
                        </div>
                      </a-radio>
                      <a-radio value="ali_pay" v-if="payChannelList.find(item => { return item.code == 'ali_pay' })">
                        <div class="flex items-center">
                          <AlipayOutlined :style="{ fontSize: '20px', color: '#057AFD' }" />
                          <span style="margin-left: 4px;">支付宝</span>
                        </div>
                      </a-radio>
                    </a-radio-group>
                  </a-form-item>

                  <div style="margin-top: 20px; text-align: right">
                    <affix :offset-bottom="20" class="mr-1">
                      <span v-if="totalMoney" style="color: #fd482c; font-size: 18px; padding-right: 10px">{{ '¥ ' +
        totalMoney }}</span>
                      <a-button type="primary" :disabled="!totalMoney" @click="pay">立即支付</a-button>
                    </affix>
                  </div>
                </a-form>
              </div>
            </div>
          </div>

          <a-result title="当前报名未开启" v-else></a-result>
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { querySpPlan, checkIdCard, simplePayCashier, queryBmInfo, queryIsAutumn, checkTicketNumber, payChannelEnable } from './Baoming.api'
import { useMessage } from '/@/hooks/web/useMessage'
import { $ref } from 'vue/macros'
import { onMounted, onUnmounted, computed, reactive } from 'vue'
import { Affix } from 'ant-design-vue'
import { FormInstance, Rule } from 'ant-design-vue/lib/form'
import useFormEdit from '/@/hooks/bootx/useFormEdit'
import { WechatOutlined, AlipayOutlined } from '@ant-design/icons-vue';

const { createMessage } = useMessage()

const { confirmLoading } = useFormEdit()

// allocation（默认false）
// amount（支付总额）;
// channel（支付渠道，阿里：ali_pay  微信：wx_pay）
// method (支付方式：wap)
// name（姓名）
// idCard（身份证）
// grade（年级，1、2、3）
// specialityId（专业ID，取专业计划里面的ID）
// collectFees （代收费）
// accDation（住宿费）
interface FormState {
  grade: number
  name: string;
  idCard: string;
  specialityId: number | null;
  collectFees: number;
  accDation: number;
  channel: string;
  method: string;
  allocation: boolean;
  ticketNumber: string;
  phone: string;
  contacts: string;
  contactsPhone: string;
  addr: string;
}

const formState = reactive<FormState>({
  grade: 1,
  name: '',
  idCard: '',
  specialityId: null,
  collectFees: 0,
  accDation: 0,
  channel: '',
  method: 'wap',
  allocation: false,
  ticketNumber: '',
  phone: '',
  contacts: '',
  contactsPhone: '',
  addr: '',
});

const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
const telRegex = /^(0|86|17951)?(1[3-9][0-9])[0-9]{8}$/;

// 校验
const rules = reactive({
  grade: [{ required: true, message: '请选择年级', trigger: 'change' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [
    { required: true, message: '请输入身份证', trigger: 'change' },
    { pattern: idCardRegex, message: '身份证格式不正确', trigger: 'blur' }
  ],
  specialityId: [{ required: true, message: '请选择专业', trigger: 'change' }],
  collectFees: [{ required: true, message: '请选择代收费', trigger: 'change' }],
  accDation: [{ required: true, message: '请选择住宿费', trigger: 'change' }],
  channel: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  ticketNumber: [{ required: true, message: '请输入填准考证号', trigger: ['blur', 'change'] }],
  phone: [
    { required: true, message: '请输入电话', trigger: ['blur', 'change'] },
    { pattern: telRegex, message: '电话格式不正确', trigger: 'blur' }
  ],
  contacts: [{ required: true, message: '请输入联系人', trigger: ['blur', 'change'] }],
  contactsPhone: [
    { required: true, message: '请输入联系人电话', trigger: ['blur', 'change'] },
    { pattern: telRegex, message: '电话格式不正确', trigger: 'blur' }
  ],
  addr: [{ required: true, message: '请输入联系地址', trigger: ['blur', 'change'] }],
} as Record<string, Rule[]>)

const formRef = $ref<FormInstance>()

let gradeList = [
  // 支付金额列表
  { label: '高一', value: 1, collectFees: 870 },
  { label: '高二', value: 2, collectFees: 870 },
  { label: '高三', value: 3, collectFees: 950 },
]

let totalMoney = computed(() => {
  return formState.collectFees + formState.accDation;
})

function computedCollectFees() {
  let grade = gradeList.find(item => {
    return item.value === formState.grade;
  })
  formState.collectFees = grade ? grade.collectFees : 0
}

computedCollectFees();

let specialityList = [];
let payChannelList = $ref<[]>([])

let initRender = $ref<boolean>(false);
let baomingIsOpen = $ref<boolean>(false);
let baomingAutumn = $ref<boolean>(false);

const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});

/**
 * 初始化业务数据
 */
function initData() {
  queryIsAutumn().then((res) => {
    console.log(res)
    initRender = true;

    for (let i = 0; i < res.data.length; i++) {
      if (res.data[i].code === 'isOpen') {
        baomingIsOpen = res.data[i].enable;
      }
      if (res.data[i].code === 'isAutumn') {
        baomingAutumn = res.data[i].enable;
      }
    }
  }).catch(err => {
    initRender = false;
  })

  querySpPlan({}).then((res) => {
    console.log(res)
    specialityList = res.data;
    if (specialityList.length > 0) {
      formState.specialityId = specialityList[0].id
    }
  })

  payChannelEnable().then(res => {
    payChannelList = res.data
    if (res.data && res.data.length > 0) {
      formState.channel = res.data[0].code
    } else {
      formState.channel = ''
    }

  }).catch()
}

function handerTicketNumber() {
  checkTicketNumber({
    ticketNumber: formState.ticketNumber
  }).then(res => {
    if (res.data) {
      if (res.data.idCard) {
        queryBmInfo({
          idCard: res.data.idCard
        }).then(res => {
          if (res.data) {
            createMessage.success('你已经报名了！')
          } else {
            createMessage.success('请尽快完成缴费报名！')
          }
        }).catch()
      } else {
        createMessage.warn('请继续填写报名信息')
      }
    }
  }).catch()
}

function handerCheckIdCard() {
  checkIdCard({
    idCard: formState.idCard
  }).then(res => {
    if (res.data) {
      queryBmInfo({
        idCard: formState.idCard
      }).then(res => {
        if (res.data) {
          createMessage.success('你已经报名了！')
        } else {
          createMessage.success('请尽快完成缴费报名！')
        }
      }).catch()
    }
  }).catch()
}

function validateIdCard() {
  return idCardRegex.test(formState.idCard);
}

/**
 * 年级
 * @param e 
 */
function gradeChange(e) {
  computedCollectFees();
}

/**
 * 发起支付. 分别处理普通支付和聚合支付
 */
async function pay() {
  formRef?.validate().then(async () => {
    confirmLoading.value = true
    // if (formState.grade === 1) {
    //   const cardData = await checkIdCard({
    //     idCard: formState.idCard
    //   }).finally(() => {
    //     confirmLoading.value = false
    //   })

    //   if (!cardData) {
    //     return;
    //   }
    // }

    const param = {
      ...formState,
      amount: totalMoney.value,
      title: '在线报名缴费',
      bizOrderNo: '123'
    }
    console.log(param)

    confirmLoading.value = true
    const { data } = await simplePayCashier(param).finally(() => {
      confirmLoading.value = false
    })
    console.log('simplePayCashier', data)
    window.location.href = data.payBody;
  })

}

/**
 * 入口
 */
onMounted(() => {
  initData()
})
/**
 * 出口
 */
onUnmounted(() => {
})
</script>

<style scoped lang="less">
@import 'style.less';
</style>
